﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Web;
using System.Xml;

namespace ImbedLibrary
{
    public class WebRequest
    {

        private static CookieContainer cookie = new CookieContainer();

        /// <summary>
        /// 登录域名白名单
        /// </summary>
        /// <param name="bai">是否登录</param>
        /// <param name="cookieUrl"></param>
        private static void LoginWhileList(bool bai, string cookieUrl)
        {
            if (bai == true)
            {
                string url = "http://xinnet.51web.com";
                string html = ImbedLibrary.WebRequest.PostWebRequest(url, "userName=wangxiaobin+&userPass=yMwe5p2u&action=%E7%99%BB%E5%BD%95", Encoding.UTF8, true, "");
                if (html.IndexOf("域名白名单") == -1)
                    throw new Exception("白名单系统登陆失败");
            }
            else
            {
                ImbedLibrary.WebRequest.PostWebRequest(cookieUrl, "", Encoding.UTF8, false, "");
            }
        }

        /// <summary>
        /// 遍历CookieContainer
        /// </summary>
        /// <param name="cc"></param>
        /// <returns></returns>
        public static List<Cookie> GetAllCookies(CookieContainer cc)
        {
            List<Cookie> lstCookies = new List<Cookie>();
            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
                System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                    | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies) lstCookies.Add(c);
            }
            return lstCookies;
        }

        /// <summary>
        /// 提交白名单到西部数码
        /// </summary>
        /// <param name="ip">服务器IP</param>
        /// <param name="domain">域名</param>
        public static void PostWhileListToWest263(string ip, string domain)
        {
            string sys_api = "http://api.west263.com/api/";
            string sys_user = "scjg2014";
            string sys_pass = "scjg888";
            //string cmdstrng = "server\r\nmanage\r\nentityname: whitelist\r\nserverip:211.149.192.3\r\n.\r\n"; //\r\n为回车换行 符
            //string cmdstrng = "server\r\nmanage\r\nentityname:addwhite\r\nserverip:" + ip + "\r\ndomain:" + domain + "\r\nicp:蜀ICP备00000000号\r\nwebname:" + webName + "\r\n.\r\n";
            //string cmdstrng = "other\r\nget\r\nentityname:usemoney\r\n.\r\n"; //\r\n为回车换行 符
            string cmdstrng = "server\r\nmanage\r\nentityname:addwhite\r\nserverip:" + ip + "\r\ndomain:" + domain + "\r\nicp:\r\nwebname:四川机构网\r\n.\r\n";


            //userid=apidemo&versig=b9f048b9232f6ec31c263711012d5891&strCmd=server%0D%0Amanage%0D%0Aentityname%3Aaddwhite%0D%0Aserverip%3A103.24.250.69%0D%0Adomain%3Awww.test.com%0D%0Aicp%3A%u8700ICP%u590700000000%u53F7%0D%0Awebname%3A%u897F%u90E8%u6570%u7801%0D%0A.%0d%0a
            //http://api.west263.com/api/?userid=scjg2014&versig=6ee41da107da36d30074922c1974aa3d&strCmd=server%0D%0Amanage%0D%0Aentityname%3Aaddwhite%0D%0Aserverip%3A103.24.250.69%0D%0Adomain%3Awww.test.com%0D%0Aicp%3A%0D%0Awebname%3A%u897F%u90E8%u6570%u7801%0D%0A.%0d%0a

            string singstr = sys_user + sys_pass + cmdstrng.Substring(0, 10);
            string md5sing = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(singstr, "MD5").ToLower();
            string postdata = "userid=" + sys_user + "&versig=" + md5sing + "&strCmd=" + HttpUtility.UrlEncode(cmdstrng, Encoding.GetEncoding("gb2312"));
            string xml = PostWebRequest(sys_api, postdata, Encoding.GetEncoding("gb2312"));
            XmlDocument xmldom = new XmlDocument();
            //dom.DocumentElement.ChildNodes

            xmldom.LoadXml(xml);
            XmlNode root = xmldom.SelectSingleNode("property");//

            string returnstatus = root.SelectNodes("returncode")[0].InnerText;
            string returnstatusmsg = root.SelectNodes("returnmsg")[0].InnerText;
            if (returnstatus != "200")
            {
                throw new Exception("E04201:西部数码提白失败," + returnstatusmsg);
            }
        }

        /// <summary>
        /// 登录西部数码
        /// </summary>
        private static void LoginWest263()
        {
            if (cookie.Count == 0)
            {
                string url = "http://www.west263.com/login.asp";
                PostWebRequest(url, "u_name=scjg2014&u_password=scjg2013&imageField.x=26&imageField.y=12", Encoding.GetEncoding("gb2312"), true);
            }
        }

        /// <summary>
        /// 获取ip地址的物理地址
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <returns>物理地址</returns>
        public static string GetIPLocaHost(string ip)
        {
            string url = "http://www.ip138.com/ips138.asp?ip=" + ip.Trim();
            string html = PostWebRequest(url,Encoding.GetEncoding("gb2312"));
            return html.Substring(html.IndexOf("<li>本站主数据：") + 4, html.IndexOf("</li>", html.IndexOf("<li>本站主数据：")) - html.IndexOf("<li>本站主数据：") - 4).Replace("本站主数据：", "").Trim();
        }

        /// <summary>
        /// 请求网页(需要cookie)
        /// </summary>
        /// <param name="postUrl">url</param>
        /// <param name="paramData">数据</param>
        /// <param name="dataEncode">编码</param>
        /// <returns></returns>
        public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode, bool bai, string cookieUrl)
        {
            string ret = string.Empty;
            HttpWebResponse response;
            StackTrace st = new StackTrace (true);
            if (cookie.Count == 0 && st.GetFrame(1).GetMethod().Name != "LoginWhileList")
                LoginWhileList(bai,cookieUrl);
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.UserAgent = "Mozilla/4.0";
                webReq.CookieContainer = cookie;
                webReq.KeepAlive = true;

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                response = (HttpWebResponse)webReq.GetResponse();
                response.Cookies = webReq.CookieContainer.GetCookies(webReq.RequestUri);
                cookie.Add(response.Cookies);
                StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception)
            {
                throw;
            }
            return ret;
        }

        private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                return "出错了";
            }
            return ret;
        }

        /// <summary>
        /// 请求网页
        /// </summary>
        /// <param name="postUrl">url</param>
        /// <param name="paramData">数据</param>
        /// <param name="dataEncode">编码</param>
        /// <param name="isNewCookies">是否使用新cookies</param>
        /// <returns></returns>
        public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode, bool isNewCookies)
        {
            string ret = string.Empty;
            HttpWebResponse response;
            StackTrace st = new StackTrace(true);
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.UserAgent = "Mozilla/4.0";
                if (isNewCookies == true)
                    webReq.CookieContainer = new CookieContainer();
                else
                    webReq.CookieContainer = cookie;
                webReq.KeepAlive = true;

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                response = (HttpWebResponse)webReq.GetResponse();
                response.Cookies = webReq.CookieContainer.GetCookies(webReq.RequestUri);
                cookie.Add(response.Cookies);
                StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception)
            {
                throw;
            }
            return ret;
        }

        /// <summary>
        /// 请求网页
        /// </summary>
        /// <param name="postUrl">url</param>
        /// <param name="dataEncode">编码</param>
        /// <returns></returns>
        public static string PostWebRequest(string postUrl, Encoding dataEncode)
        {
            postUrl = postUrl.Trim();
            if (postUrl.IndexOf("http://") != 0) postUrl = "http://" + postUrl;
            string ret = string.Empty;
            HttpWebResponse response;
            StackTrace st = new StackTrace(true);
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(postUrl));
                webRequest.Method = "Get";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.UserAgent = "Mozilla/4.0";
                webRequest.KeepAlive = true;

                response = (HttpWebResponse)webRequest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();

            }
            catch (Exception e)
            {

                throw;
            }
            return ret;
        }

    }
}
